import { defineStore } from 'pinia';
import { loginApi, getUserInfoApi } from '@/api/user';
import { getMenuListApi } from '@/api/menu';

import { generateRoutes } from '@/router/dynamic';
import router from '../router'


export const useUserStore = defineStore('user', {
    state: () => ({
        token: localStorage.getItem('token') || '',
        userInfo: null,
        menus: [],
        routesAdded: false,
        isLogin: false,
        menuList: []
    }),
    actions: {
        async login(username, password) {
            const { token } = await loginApi({ username, password });
            this.token = token;
            localStorage.setItem('token', token);
            router.push('/')
        },
        async loadUserData() {
            // 获取用户信息
            // this.userInfo = await getUserInfoApi();
            // 获取菜单
            const menus = await getMenuListApi();
            this.menus = menus.menus
            // 生成并挂载路由
            const routes = generateRoutes(this.menus);
            this.menuList = this.menus
            // 动态生成路由
            routes.forEach(r => router.addRoute(r));
            this.routesAdded = true;
            this.isLogin = true
        },
        logout() {
            this.token = '';
            this.userInfo = null;
            this.menus = [];
            this.routesAdded = false;
            his.isLogin = false
            localStorage.removeItem('token');
            router.push('/login');
        }
    }
})
